1.code
import React, { useState } from 'react';
import styles from './ImageZoomPreview.module.css';
function ImageZoomPreview({ imageUrl }) {
//使用狀態來追蹤圖像是否被放大和鼠標位置
const [zoomed, setZoomed] = useState(false);
const [cursorPosition, setCursorPosition] = useState({ x: 0, y: 0 });
//處理鼠標進入容器的事件
const handleMouseEnter = (e) => {
setZoomed(true);//設置圖像為放大狀態
setCursorPosition(getCursorPosition(e));//獲取當前鼠標位置
};
//處理鼠標移動事件
const handleMouseMove = (e) => {
setCursorPosition(getCursorPosition(e));//更新鼠標位置
};
//處理鼠標離開容器的事件
const handleMouseLeave = () => {
setZoomed(false);//恢復圖像到正常大小
};
//獲取鼠標相對於圖像容器的位置
const getCursorPosition = (e) => {
const { left, top, width, height } = e.target.getBoundingClientRect();
const x = (e.clientX - left) / width;
const y = (e.clientY - top) / height;
return { x, y };
};
return (
<div
className={styles.container}
onMouseEnter={handleMouseEnter}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
>
<div
className={`${styles.image} ${zoomed ? styles.zoomed : ''}`}
style={{
backgroundImage: `url(${imageUrl})`,
backgroundPosition: `${cursorPosition.x * 100}% ${
cursorPosition.y * 100
}%`,
}}
></div>
</div>
);
}
export default ImageZoomPreview;
.container {
position: relative;
width: 300px;
height: 300px;
overflow: hidden;
}
.image {
width: 100%;
height: 100%;
background-size: 100% 100%;
transition: transform 0.2s ease-in-out;
}
.image.zoomed {
transform: scale(1.5); //調整放大倍數
transition: transform 0.2s ease-in-out;
}
export default function FirstPost() {
const imageUrl = '自定義圖片';
return (
<Layout>
<Head>
<title>Test</title>
</Head>
<h1>Test</h1>
<div>
<h1>Image Zoom Preview</h1>
<ImageZoomPreview imageUrl={imageUrl} />
</div>
<h3><Link href="/">back to home</Link> </h3>
</Layout>
);
}
2.實作